package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper=new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        String blogId=req.getParameter("blogId");
        BlogDao blogDao=new BlogDao();
        if (blogId==null){
            //如果为空，则是获取博客列表
            List<Blog> blogList=blogDao.queryBlogAll();
            String blogListJson=objectMapper.writeValueAsString(blogList);
            resp.getWriter().write(blogListJson);
        }else{
            //带了参数则是获取博客详情
            Blog blog=blogDao.queryBlogById(Integer.parseInt(blogId));
            String blogJson=objectMapper.writeValueAsString(blog);

            resp.getWriter().write(blogJson);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理发布blog页面逻辑
        req.setCharacterEncoding("utf8");
        //1.获取用户状态信息
        HttpSession session=req.getSession(false);
        if (session==null){
            resp.setStatus(403);
            return;
        }
        User user= (User) session.getAttribute("user");
        if (user==null){
            resp.setStatus(403);
            return;
        }
        //2.获取登录参数
        String title=req.getParameter("title");
        String content=req.getParameter("content");
        //3.生成blog实体
        if (title==null||content==null||title==""||content==""){
            resp.setStatus(400);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("标题或内容为空！请重新输入");
            return;
        }
        Blog blog=new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        System.out.println(user.getUserId());
        //4.将实体写入数据库
        BlogDao blogDao=new BlogDao();
        blogDao.insert(blog);
        //5.重定向
        resp.sendRedirect("blog_list.html");

    }
}
